package com.lechi.iot.netty.utils;


import java.io.IOException;
import java.io.OutputStream;

/**
 * A streaming Hex encoder.
 */
public class HexEncoder {
    protected final byte[] encodingTable =
            {
                    (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
                    (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f'
            };

    /*
     * set up the decoding table.
     */
    protected final byte[] decodingTable = new byte[128];

    public HexEncoder() {
        initialiseDecodingTable();
    }

    protected void initialiseDecodingTable() {
        for (int i = 0; i < decodingTable.length; i++) {
            decodingTable[i] = (byte) 0xff;
        }

        for (int i = 0; i < encodingTable.length; i++) {
            decodingTable[encodingTable[i]] = (byte) i;
        }

        decodingTable['A'] = decodingTable['a'];
        decodingTable['B'] = decodingTable['b'];
        decodingTable['C'] = decodingTable['c'];
        decodingTable['D'] = decodingTable['d'];
        decodingTable['E'] = decodingTable['e'];
        decodingTable['F'] = decodingTable['f'];
    }

    public int encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) throws IOException {
        int inPos = inOff;
        int inEnd = inOff + inLen;
        int outPos = outOff;

        while (inPos < inEnd) {
            int b = inBuf[inPos++] & 0xFF;

            outBuf[outPos++] = encodingTable[b >>> 4];
            outBuf[outPos++] = encodingTable[b & 0xF];
        }

        return outPos - outOff;
    }

    public void encode(byte[] buf, int off, int len, OutputStream out)
            throws IOException {
        if (len < 0) {
            return;
        }

        byte[] tmp = new byte[72];
        int remaining = len;
        while (remaining > 0) {
            int inLen = Math.min(36, remaining);
            int outLen = encode(buf, off, inLen, tmp, 0);
            out.write(tmp, 0, outLen);
            off += inLen;
            remaining -= inLen;
        }
    }
}
